package com.hotec.PROJECT_NAME.utils;

import cn.hutool.core.io.FileUtil;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;

public class PdfWatermarkUtil {
    /**
     * 给PDF添加水印
     * @param inputFile 原文件
     * @param outputFile 添加水印后输出文件
     * @param waterMarkText 添加水印的内容
     */
    public static void addWatermark(File inputFile, File outputFile, String waterMarkText) {
        try {
            // 水印的高和宽（参数可调节）
            int textH = 75;
            int textW = 170;
            // 间隔距离（参数可调节）
            int interval = 15;

            PdfReader reader = new PdfReader(FileUtil.getInputStream(inputFile));
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            BaseFont base = BaseFont.createFont();
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.3f);//改透明度
            gs.setStrokeOpacity(0.4f);
            int total = reader.getNumberOfPages() + 1;
            JLabel label = new JLabel();
            PdfContentByte under;

            // 可添加多个水印
            Rectangle pageRect = null;
            FontMetrics metrics;
            label.setText(waterMarkText);
            metrics = label.getFontMetrics(label.getFont());
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                // 在内容上方加水印
                under = stamper.getOverContent(i);
                // 在内容下方加水印
                //under = stamper.getUnderContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(base, 20);
                // 水印文字成30度角倾斜
                for (int height = interval + textH; height < pageRect.getHeight();
                     height = height + textH * 3) {
                    for (int width = interval + textW; width < pageRect.getWidth() + textW;
                         width = width + textW * 2) {
                        under.showTextAligned(Element.ALIGN_LEFT
                                , waterMarkText, width - textW,
                                height - textH, 25);
                    }
                }
                // 添加水印文字
                under.endText();
            }
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
